import { http } from '@/utils/request'
import type { UserInfo } from './auth'

// 用户统计信息
export interface UserStats {
  account_count: number
  category_count: number
  device_count: number
  last_login?: string
}

// 用户信息响应
export interface UserInfoResponse {
  user: UserInfo
  stats: UserStats
}

// 更新用户信息数据
export interface UpdateUserInfoData {
  nickname?: string
  avatar?: string
  master_key_hint?: string
}

// 修改密码数据
export interface ChangePasswordData {
  old_password: string
  new_password: string
}

// 设备信息
export interface DeviceInfo {
  id: number
  device_id: string
  device_name?: string
  platform: string
  platform_name: string
  device_info: any
  encrypt_method: string
  app_version?: string
  last_active?: string
  ip_address?: string
  created_at: string
  device_display: string
}

// 操作日志
export interface UserLog {
  id: number
  action: string
  action_name: string
  description?: string
  ip?: string
  platform?: string
  device_id?: string
  created_at: string
}

// 活跃统计
export interface ActiveStats {
  date: string
  count: number
}

/**
 * 获取用户信息
 */
export const getUserInfo = () => {
  return http.get<UserInfoResponse>('/user/info')
}

/**
 * 更新用户信息
 */
export const updateUserInfo = (data: UpdateUserInfoData) => {
  return http.put<UserInfo>('/user/info', data, {
    loading: true,
    loadingText: '更新中...'
  })
}

/**
 * 修改密码
 */
export const changePassword = (data: ChangePasswordData) => {
  return http.put('/user/password', data, {
    loading: true,
    loadingText: '修改中...'
  })
}

/**
 * 修改加密方式
 */
export const changeEncryptMethod = (deviceId: string, encryptMethod: string) => {
  return http.put('/user/encrypt-method', {
    device_id: deviceId,
    encrypt_method: encryptMethod
  }, {
    loading: true,
    loadingText: '更新中...'
  })
}

/**
 * 获取设备列表
 */
export const getDevices = () => {
  return http.get<DeviceInfo[]>('/user/devices')
}

/**
 * 删除设备
 */
export const deleteDevice = (deviceId: string) => {
  return http.delete('/user/devices', {
    data: { device_id: deviceId },
    loading: true,
    loadingText: '删除中...'
  })
}

/**
 * 获取操作日志
 */
export const getUserLogs = (params?: {
  page?: number
  limit?: number
  action?: string
}) => {
  return http.get<{
    data: UserLog[]
    total: number
    per_page: number
    current_page: number
  }>('/user/logs', params)
}

/**
 * 获取最近登录记录
 */
export const getRecentLogins = (limit: number = 10) => {
  return http.get<UserLog[]>('/user/recent-logins', { limit })
}

/**
 * 获取活跃统计
 */
export const getActiveStats = (days: number = 30) => {
  return http.get<ActiveStats[]>('/user/active-stats', { days })
}

/**
 * 注销账户
 */
export const deleteAccount = (password: string) => {
  return http.delete('/user/account', {
    data: { password },
    loading: true,
    loadingText: '注销中...'
  })
}